//
//  HeadImageCell.m
//  VICKY ZONE
//
//  Created by sunx on 15/3/24.
//  Copyright (c) 2015年 sunx. All rights reserved.
//

#import "HeadImageCell.h"
#import "ImageLoader.h"
#import "SVProgressHUD.h"

@interface HeadImageCell()
@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,strong) NSString *imageURL;
@property int time;
@end
@implementation HeadImageCell
@synthesize imageView;

-(instancetype)initWithImageURL:(NSString *)imageURL {
    self = [super init];
    
    self.backgroundColor = [UIColor clearColor];
    CGRect rect = [ UIScreen mainScreen ].applicationFrame;

    self.imageView = [[UIImageView alloc] init];
    self.imageURL = imageURL;
    self.time = 0;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(refreshSelf) userInfo:nil repeats:YES];
    
    UIImage *image = [ImageLoader loardImageToDocuments:imageURL];

    if(image == nil) {
        image = [UIImage imageNamed:@"header"];
        [self.timer fire];
        [SVProgressHUD show];
    }
    self.imageView.image = image;
    
    
    float width = rect.size.width;
    float height = rect.size.height;
    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(width*0.5 - height*0.18 *0.5,0,height *0.18,height *0.18)];
    circle.backgroundColor = [UIColor clearColor];
    circle.layer.borderWidth = 2;
    circle.layer.borderColor = [[UIColor grayColor] CGColor];
    circle.layer.masksToBounds = YES;
    circle.layer.cornerRadius = height*0.18 * 0.5;
    [self addSubview:circle];
    
    self.imageView.frame = CGRectMake(width*0.5 - height*0.16 *0.5, height * 0.01, height *0.16, height*0.16);
    self.imageView.layer.masksToBounds=YES;
    self.imageView.layer.cornerRadius = height*0.16 *0.5;
    [self addSubview:self.imageView];
    self.height = height*0.18;
    
    return self;
}
-(void)refreshSelf {
    if(self.time > 10) {
        [self.timer invalidate];
        [SVProgressHUD dismiss];
    }else {
        self.time++;
        NSLog(@"loading...");
        UIImage *image = [ImageLoader loardImageToDocuments:self.imageURL];
        if(image != nil) {
            self.imageView.image = image;
            [self.timer invalidate];
            [SVProgressHUD dismiss];
        }
    }
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
